package org.cainiao.api.lark.util;

import lombok.experimental.UtilityClass;
import org.cainiao.api.lark.impl.util.provider.AccessTokenProvider;
import org.cainiao.api.lark.impl.util.provider.LarkAccessTokenProvider;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@UtilityClass
public class Util {

    public static final String AUTH_MODULE_URI = "/auth/v3";
    public static final String AUTHEN_MODULE_URI = "/authen/v1";
    public static final String DRIVE_MODULE_URI = "/drive/v1";
    public static final String DOCX_MODULE_URI = "/docx/v1";
    public static final String BOARD_MODULE_URI = "/board/v1";

    public static void setAccessToken(
        WebClient.RequestHeadersSpec<? extends WebClient.RequestHeadersSpec<?>> requestHeadersSpec,
        AccessTokenProvider accessTokenProvider) {

        String accessToken = accessTokenProvider == null ? null : accessTokenProvider.getAccessToken();
        if (StringUtils.hasText(accessToken)) {
            requestHeadersSpec.header("Authorization", String.format("Bearer %s", accessToken));
        }
    }

    public static WebClient.RequestHeadersSpec<? extends WebClient.RequestHeadersSpec<?>> getByMediaTypeWithAccessToken(
        WebClient webClient, String url, LarkAccessTokenProvider larkAccessTokenProvider, MediaType mediaType) {

        WebClient.RequestHeadersSpec<? extends WebClient.RequestHeadersSpec<?>> requestHeadersSpec = webClient
            .get().uri(url).accept(mediaType);
        setAccessToken(requestHeadersSpec, larkAccessTokenProvider);
        return requestHeadersSpec;
    }

    public static WebClient.RequestHeadersSpec<? extends WebClient.RequestHeadersSpec<?>> getJsonWithAccessToken(
        WebClient webClient, String url, LarkAccessTokenProvider larkAccessTokenProvider) {

        return getByMediaTypeWithAccessToken(webClient, url, larkAccessTokenProvider, MediaType.APPLICATION_JSON);
    }

    public static WebClient.RequestHeadersSpec<? extends WebClient.RequestHeadersSpec<?>> getPngWithAccessToken(
        WebClient webClient, String url, LarkAccessTokenProvider larkAccessTokenProvider) {
        
        return getByMediaTypeWithAccessToken(webClient, url, larkAccessTokenProvider, MediaType.IMAGE_PNG);
    }
}
